import { makeAutoObservable } from 'mobx';
import { Bean } from '../beans';

type EventHandler = (...args: any[]) => void;

@Bean('eventController')
export class EventController {
  private eventMap: Map<string, EventHandler[]> = new Map();

  constructor() {
    makeAutoObservable(this);
  }

  emit(eventName: string, ...args: any[]) {
    const handlers = this.eventMap.get(eventName);
    if (handlers) {
      handlers.forEach(handler => handler(...args));
    }
  }

  on(eventName: string, handler: EventHandler) {
    if (!this.eventMap.has(eventName)) {
      this.eventMap.set(eventName, []);
    }
    this.eventMap.get(eventName)!.push(handler);
  }

  off(eventName: string, handler: EventHandler) {
    const handlers = this.eventMap.get(eventName);
    if (handlers) {
      const index = handlers.indexOf(handler);
      if (index > -1) {
        handlers.splice(index, 1);
      }
    }
  }
} 